<template>
  <article class="page page-webapi-clipboard">
    <h4 class="text-center">WebAPI Clipboard</h4>
    <form role="form">
      <div class="form-group">
        <label class="col-form-label">文本内容</label>
        <textarea class="form-control" v-model="text" placeholder="请输入内容" rows="6" ></textarea>
      </div>
      <div class="form-group">
        <label class="col-form-label">剪贴板操作</label>
        <pre>{{actions.join('、')}}</pre>
      </div>
      <div class="form-group">
        <label class="col-form-label">剪贴板内容</label>
        <pre>{{clipText}}</pre>
      </div>
      <div class="form-group">
        <label class="col-form-label">剪贴板追加内容</label>
        <input class="form-control" v-model="suffixText" placeholder="请输入剪贴板追加内容" />
      </div>
    </form>
  </article>
</template>

<script>
export default {
  name: 'webapi-clipboard',
  data () {
    return {
      clipboard: null,
      actions: [],
      text: '',
      clipText: '',
      suffixText: '版权所有之类的文字'
    }
  },
  mounted () {
    this.bindEvent()
  },
  beforeDestroy () {
    this.removeEvent()
  },
  methods: {
    bindEvent () {
      window.addEventListener('copy', this.copyHandler)
      window.addEventListener('cut', this.cutHandler)
      window.addEventListener('paste', this.pasteHandler)
    },
    removeEvent () {
      window.removeEventListener('copy', this.copyHandler)
      window.removeEventListener('cut', this.cutHandler)
      window.removeEventListener('paste', this.pasteHandler)
    },
    // 复制
    copyHandler (e) {
      this.actions.push('复制')
      console.log('复制:', e)
      this.getClipboardText().then(() => {
        this.setClipboardText()
      })
    },
    // 剪切
    cutHandler (e) {
      this.actions.push('剪切')
      console.log('剪切:', e)
      this.getClipboardText().then(() => {
        this.setClipboardText()
      })
    },
    // 粘贴
    pasteHandler (e) {
      this.actions.push('粘贴')
      console.log('粘贴:', e)
    },
    // 剪切板文字数据-读取
    getClipboardText () {
      if (!navigator.clipboard) {
        return Promise.reject('当前浏览器不支持navigator.clipboard')
      } else {
        return navigator.clipboard.readText().then(clipText => {
          this.clipText = clipText
        })
      }
    },
    // 剪切板文字数据-写入
    setClipboardText () {
      if (!navigator.clipboard) {
        return Promise.reject('当前浏览器不支持navigator.clipboard')
      } else {
        let text = this.suffixText ? `${this.clipText}\r\n${this.suffixText}` : this.clipText
        return navigator.clipboard.writeText(text)
      }
    }
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
pre {
  white-space: pre-wrap;
}
</style>
